package com.module.check.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import base.dao.GenericHibernateDao;
import base.util.Page;

import com.module.check.vo.CheckTask;
import com.module.check.vo.PersonalTask;

public class PersonalTaskDao  extends GenericHibernateDao<PersonalTask, Long> {
	
	private PersonalTaskDao(){}
	
	private static PersonalTaskDao dao;
	
	public synchronized static PersonalTaskDao getInstance(){
		if(dao==null)
			dao = new PersonalTaskDao();
		return dao;
	}
	/**
	 * 查询稽查任务列表
	 * @param session
	 * @param bean
	 * @param start
	 * @param limit
	 * @return
	 * @throws SQLException
	 */
	public Page getList(Session session,PersonalTask bean,Integer start, Integer limit)throws SQLException{
		Page page = new Page();
		StringBuffer sb = new StringBuffer();
	    StringBuffer condition = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		
		if(bean.getStatus()!=null&&!"".equals(bean.getStatus())){
			condition.append(" and obj.status like ?");
			params.add("%"+bean.getStatus() + "%");
		}
		if(bean.getTaskId()!=0){
			condition.append(" and obj.taskId = ?");
			params.add(bean.getTaskId());
		}
		
		if(bean.getType()!=null&&!"".equals(bean.getType())){
			condition.append(" and obj.type = ?");
			params.add(bean.getType());
		}
		if(bean.getUserId()!=null&&!"".equals(bean.getUserId())){
			condition.append(" and obj.userId = ?");
			params.add(bean.getUserId());
		}
		sb.append("from PersonalTask as obj where 1=1 ");
		sb.append(condition);
		sb.append(" order by id desc");
	
		Query query = session.createQuery(sb.toString());
	        int i = 0;
			for (Object obj : params) {
				query.setParameter(i, obj);
				i++;
			}
		query.setFirstResult(start).setMaxResults(limit);
		
		Query totalQuery = session
		.createQuery("select count(*) from PersonalTask as obj where 1=1 "+condition);
		int j = 0;
		for (Object obj : params) {
			totalQuery.setParameter(j, obj);
			j++;
		}
		page.setTotal((long) ((Long) totalQuery.uniqueResult()).intValue());

		List<Object> plist= query.list();
		Long taskId = (long) 0;
		String taskDetail = "";
		for (Object personalTask : plist) {
			if(taskId !=((PersonalTask) personalTask).getTaskId()){
				taskId = ((PersonalTask) personalTask).getTaskId();
				Query task = session.createQuery("from CheckTask where id = "+((PersonalTask) personalTask).getTaskId());
				List<CheckTask> tasklist = task.list();
				if(tasklist.size()>0)
					taskDetail = tasklist.get(0).getDetail();
			}
				((PersonalTask) personalTask).setDetail(taskDetail);

		}
		page.setRows(plist);	
		return page;
	}
}

